<template>
  <div class="profile-page">
    <van-nav-bar
      title="个人中心"
      left-arrow
      @click-left="onClickLeft"
    />
    
    <div class="page-container">
      <div class="user-card">
        <div class="avatar">
          <img :src="userInfo.avatar || '/default-avatar.png'" alt="头像" />
        </div>
        <div class="user-info">
          <div class="username">{{ userInfo.username }}</div>
          <div class="join-date">注册时间: {{ formatDate(userInfo.createdAt) }}</div>
        </div>
      </div>
      
      <div class="stats-section">
        <div class="section-title">游戏统计</div>
        <div class="stats-content">
          <div class="stat-item">
            <div class="stat-value">{{ userStats.totalGames || 0 }}</div>
            <div class="stat-label">总局数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ userStats.completedGames || 0 }}</div>
            <div class="stat-label">完成局数</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ calculateWinRate() }}%</div>
            <div class="stat-label">完成率</div>
          </div>
        </div>
      </div>
      
      <div class="best-records">
        <div class="section-title">最佳记录</div>
        <van-cell-group inset>
          <van-cell title="简单模式" :value="formatTime(bestRecords.easy)" />
          <van-cell title="中等模式" :value="formatTime(bestRecords.medium)" />
          <van-cell title="困难模式" :value="formatTime(bestRecords.hard)" />
        </van-cell-group>
      </div>
      
      <div class="actions-section">
        <van-button 
          type="primary" 
          block 
          icon="replay"
          @click="goToGame"
        >
          开始游戏
        </van-button>
        
        <van-button 
          type="default" 
          block 
          icon="bar-chart-o"
          @click="goToLeaderboard"
          class="mt-10"
        >
          查看排行榜
        </van-button>
        
        <van-button 
          type="danger" 
          block 
          icon="close"
          @click="confirmLogout"
          class="mt-10"
        >
          退出登录
        </van-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../store/user';
import { Dialog, Toast } from 'vant';

const router = useRouter();
const userStore = useUserStore();

const userInfo = ref({
  username: '',
  avatar: '',
  createdAt: ''
});

const userStats = ref({
  totalGames: 0,
  completedGames: 0
});

const bestRecords = ref({
  easy: null,
  medium: null,
  hard: null
});

// 计算胜率
const calculateWinRate = () => {
  if (userStats.value.totalGames === 0) return 0;
  const rate = (userStats.value.completedGames / userStats.value.totalGames) * 100;
  return Math.round(rate);
};

// 格式化时间
const formatTime = (seconds) => {
  if (!seconds) return '--:--';
  
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit' 
  });
};

// 前往游戏页面
const goToGame = () => {
  router.push('/');
};

// 前往排行榜
const goToLeaderboard = () => {
  router.push('/leaderboard');
};

// 确认退出登录
const confirmLogout = () => {
  Dialog.confirm({
    title: '提示',
    message: '确定要退出登录吗？',
  })
    .then(async () => {
      const result = await userStore.userLogout();
      if (result) {
        Toast.success('已退出登录');
        router.replace('/');
      } else {
        Toast.fail('退出登录失败');
      }
    })
    .catch(() => {
      // 取消操作
    });
};

// 返回按钮点击事件
const onClickLeft = () => {
  router.back();
};

// 获取用户信息
const fetchUserData = async () => {
  if (!userStore.isLoggedIn) {
    router.replace('/login');
    return;
  }
  
  // 如果还没有用户信息，从服务器获取
  if (!userStore.userInfo) {
    await userStore.fetchUserInfo();
  }
  
  if (userStore.userInfo) {
    userInfo.value = userStore.userInfo;
    
    // 在实际应用中，这里应该有专门的API获取用户统计信息和最佳记录
    // 这里用模拟数据
    userStats.value = {
      totalGames: userStore.userInfo.totalGames || 0,
      completedGames: userStore.userInfo.completedGames || 0
    };
    
    bestRecords.value = {
      easy: userStore.userInfo.bestRecords?.easy || null,
      medium: userStore.userInfo.bestRecords?.medium || null,
      hard: userStore.userInfo.bestRecords?.hard || null
    };
  }
};

onMounted(async () => {
  await fetchUserData();
});
</script>

<style scoped>
.profile-page {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.user-card {
  margin: 15px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(100, 101, 102, 0.12);
  display: flex;
  align-items: center;
}

.avatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 15px;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-info {
  flex: 1;
}

.username {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.join-date {
  font-size: 14px;
  color: #969799;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  padding: 0 15px;
}

.stats-section {
  margin-bottom: 20px;
}

.stats-content {
  display: flex;
  padding: 0 15px;
}

.stat-item {
  flex: 1;
  text-align: center;
  padding: 15px 0;
  background-color: #fff;
  border-radius: 8px;
  margin: 0 5px;
  box-shadow: 0 2px 12px rgba(100, 101, 102, 0.08);
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #1989fa;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #969799;
}

.best-records {
  margin-bottom: 20px;
}

.actions-section {
  padding: 0 15px;
  margin-top: 30px;
}
</style>
